/*
    Kudip, Cute UDP listener
    Copyright (C) 2012 Julio Molina Soler <jmolinaso@gmail.com>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

#include "kudip.h"
#include "ui_kudip.h"
#include <QDateTime>
#include <QFileDialog>
#include <QMessageBox>

kudip::kudip(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::kudip)
{
    ui->setupUi(this);
    UdpListenerSocket = new QUdpSocket(this);
    selectedPort = 0;
}

kudip::~kudip()
{
    delete ui;
}

void kudip::readPendingDatagrams()
{
    while(UdpListenerSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(UdpListenerSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        UdpListenerSocket->readDatagram(datagram.data(), datagram.size(),
                                &sender, &senderPort);

        sendMessageToMain("DATAGRAM",datagram);

    }
}

// UI actions
void kudip::on_startButton_clicked()
{
    selectedPort = ui->portEdit->text().toInt();

    if (UdpListenerSocket->bind(selectedPort))
    {
        connect(UdpListenerSocket, SIGNAL(readyRead()),
                     this, SLOT(readPendingDatagrams()));
        sendMessageToMain("FEEDBACK","Start listening on port " + QString::number(selectedPort));
    }
    else
    {
        if (selectedPort < 1025 )
        {
            sendMessageToMain("FEEDBACK","Port " + QString::number(selectedPort)
                              + " can only be open with admin rights.");
        }
        else
        {
            sendMessageToMain("FEEDBACK","Port " + QString::number(selectedPort)
                              + " in used.");
        }

    }

}

void kudip::on_stopButton_clicked()
{
    if (selectedPort > 0)
    {
        UdpListenerSocket->close();
        sendMessageToMain("FEEDBACK","Stop listening on port "+QString::number(selectedPort));
    }
}

void kudip::sendMessageToMain(QString type,QString message)
{
    QDateTime now = QDateTime::currentDateTime();
    QString msg = now.toString("dd-MM-yyyy hh:mm:ss.zzz") + " [" + type + "] " + message;
    ui->mainTextView->appendPlainText(msg);
    if (ui->autoSaveCheckBox->isChecked())
    {
        writeToFile(msg);

    }
}

void kudip::on_saveButton_clicked()
{
    QString newFileName = QFileDialog::getSaveFileName(this,tr("Save current view"),"",tr("Text File (*.txt);;All Files (*)"));

    if (newFileName.isEmpty())
    {
        sendMessageToMain("FEEDBACK","Current view not saved, no file name provided.");
    }
    else
    {
        QFile file(newFileName);
        if (!file.open(QIODevice::WriteOnly  | QFile::Text))
        {
            QMessageBox::warning(this, tr("Kudip"),
                                          tr("Cannot write file %1:\n%2.")
                                          .arg(newFileName)
                                          .arg(file.errorString()));
            sendMessageToMain("FEEDBACK",tr("Cannot write file %1:\n%2.")
                              .arg(newFileName)
                              .arg(file.errorString()));
        }
        else
        {
            QTextStream out(&file);
            out << ui->mainTextView->toPlainText();
            file.close();
        }
    }
}

void kudip::on_autoSaveCheckBox_clicked()
{
    if (ui->autoSaveCheckBox->isChecked() && filename.isEmpty())
    {
        filename = QFileDialog::getSaveFileName(this,tr("Save current view"),"",tr("Text File (*.txt);;All Files (*)"));
    }

    if (filename.isEmpty())
    {
        ui->autoSaveCheckBox->setChecked(false);
    }
}

void kudip::writeToFile(QString message)
{
    if (!filename.isEmpty() || !filename.isNull())
    {
        QFile file(filename);
        if (!file.open(QIODevice::Append  | QFile::Text))
        {
            QMessageBox::warning(this, tr("Kudip"),
                                          tr("Cannot write file %1:\n%2.")
                                          .arg(filename)
                                          .arg(file.errorString()));
            sendMessageToMain("FEEDBACK",tr("Cannot write file %1:\n%2.")
                              .arg(filename)
                              .arg(file.errorString()));
        }
        else
        {
            QTextStream out(&file);
            out << message << "\n";
            file.close();
        }
    }
}

void kudip::on_aboutButton_clicked()
{
    QMessageBox::about(this,QString("Kudip"),QString("Author Julio Molina Soler <jmolinaso@gmail.com>"));
}
